const connections = require('../app/database')
class CartService {
  async create(userId) {
    try {
      const statement = 'SELECT * FROM `goods-cart` WHERE userId = ?'
      const res = await connections.execute(statement, [userId])
      return res[0]
    } catch (error) {
      console.log(error);
    }
  }
  async updateCountService(userId, goodsId, newCount) {
    try {
      const statement = 'UPDATE `goods-cart` SET count = ? WHERE userId = ? AND goodsId = ?'
      const res = await connections.execute(statement, [newCount, userId, goodsId])
      return res[0]
    } catch (error) {
      console.log(error)
      return false
    }
  }
  async deleteCartService(id) {
    try {
      const statement = 'DELETE FROM `goods-cart` WHERE id = ?'
      const res = await connections.execute(statement, [id])
      return res[0]
    } catch (error) {
      console.log(error)
      return false
    }
  }
  async addCartService(goodsId, userId, count) {
    let title, price, imgUrl = ''
    try {
      const result = await connections.execute('SELECT title, price, imgUrl FROM `goods-info` WHERE id = ? ', [goodsId])
      title = result[0][0].title
      price = result[0][0].price
      imgUrl = result[0][0].imgUrl
    } catch (error) {
      console.log(error);
    }
    try {
      const statement = 'INSERT INTO `goods-cart`(goodsId, userId, title, price, imgUrl, count) VALUES (?, ?, ?, ?, ?, ?)'
      const res = await connections.execute(statement, [goodsId, userId, title, price, imgUrl, count])
      return res[0]
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = new CartService()